axios.defaults.baseURL='http://ajax-base-api-t.itheima.net'
const tb=document.querySelector('#tb')
const form=document.querySelector('#bookForm')
const shaixuan=document.querySelector('.shaixuan')
const  pic=async ()=>{
  const {data:res}=await axios.get('/api/getbooks')
    const {data}=res

   const html= data.map(function(item){
      return ` <tr>
      <td>${item.id}</td>
      <td>${item.bookname}</td>
      <td>${item.author}</td>
      <td>${item.publisher}</td>
      <td><a href="#" data-id="${item.id}">删除</a></td>
    </tr>`
    }).join('')
tb.innerHTML=html
 
}
pic()

form.addEventListener('submit',async function(e){
  e.preventDefault()
  const data= serialize(form,{hash:true})
  const {data:res} =await axios.post('/api/addbook',data)
    alert(res.msg)
    if(res.status !==201) return
    this.reset()
    pic() 
 
})

tb.addEventListener('click',async function(e){
  if(e.target.tagName==='A'){
    const add= e.target.dataset.id
    const {data:res}= await axios.get('/api/delbook?id='+add)
      pic()
   
  }
}) 


async function xx(a){
 const {data:res} = await axios({
    url:'/api/getbooks',
    // method:'GET',
    params:a
  })
    const {data}=res
    tb.innerHTML=data.map((item)=>{
      return ` <tr>
      <td>${item.id}</td>
      <td>${item.bookname}</td>
      <td>${item.author}</td>
      <td>${item.publisher}</td>
      <td><a href="#" data-id="${item.id}">删除</a></td>
    </tr>`
    }).join('')

}
shaixuan.addEventListener('click',function(){
  const shaixuan1= serialize(form,{hash:true}) 
  xx(shaixuan1)
  })



// function xx(data){
//   const html= data.map(function(item){
//     return ` <tr>
//     <td>${item.id}</td>
//     <td>${item.bookname}</td>
//     <td>${item.author}</td>
//     <td>${item.publisher}</td>
//     <td><a href="#" data-id="${item.id}">删除</a></td>
//   </tr>`
//   }).join('')
// tb.innerHTML=html
// }

// shaixuan.addEventListener('click',function(){
//   const shaixuan1= serialize(form,{hash:true}) 
//   const arr1=[]
//   // console.log(shaixuan1);
//   // console.log(shaixuan1.bookname);
//   axios({
//     url:'/api/getbooks'
// }).then(({data:res})=>{
//   const {data}=res
//   // console.log(data);
//   data.forEach(function(item){
//     // console.log(item.bookname===shaixuan1.bookname&&item.author===shaixuan1.author&&item.publisher===shaixuan1.publisher);
//     // console.log(item.bookname);
//     // console.log(shaixuan1.bookname);
//     if(item.bookname===shaixuan1.bookname&&item.author===shaixuan1.author&&item.publisher===shaixuan1.publisher){
//     //  console.log(item.bookname===shaixuan1.bookname);
//     // console.log(item);
//      arr1.push(item)
//     //  console.log(arr1);
//      xx(arr1)
//     }
//   })
// })
// })
